<template>
  <div class="clock-in">
    <div class="info-content">
      <div class="info-top">
        <span><van-icon name="clock-o" size="24" class="clock-icon" /> 考勤打卡</span>
      </div>
      <van-button type="danger" v-if="currentTaskId||username" @click="clearCache" icon="delete-o">
        清空缓存
      </van-button>
      <div class="clock-panel">
        <div class="time-display">
          <h2>{{ currentTime }}</h2>
          <p>{{ currentDate }}</p>
        </div>
        <div class="clock-actions">
          <van-button type="primary" size="large" @click="showTasks" icon="plus">
            {{ !tasks.username ? '创建任务' : '修改任务' }}
          </van-button>
          <van-button type="success" size="large" @click="executeTask(tasks.id)" icon="clock">
            手动执行
          </van-button>
        </div>
      </div>
      <div class="task-list" v-if="tasks.username">
        <h3>
          <div><van-icon name="todo-list-o" /> 任务信息</div>
          <div style="display: flex; align-items: center; justify-content: flex-end">
            <van-switch v-model="taskStatus" @change="() => (taskStatus ? resumeTask(tasks.id) : pauseTask(tasks.id))"
              size="20" style="margin-right: 10px;" />
            <van-button @click="deleteTask(tasks.id)" size="mini" type="danger">删除任务</van-button>
          </div>
        </h3>
        <van-list>
          <van-cell :title="tasks.username" class="task-cell">
            <template #label>
              <div class="task-info">
                <p><van-icon name="sign" /> 上班时间: {{ tasks.clockIn }}</p>
                <p><van-icon name="completed" /> 下班时间: {{ tasks.clockOut }}</p>
                <p><van-icon name="envelop-o" /> 邮箱: {{ tasks.email }}</p>
                <p><van-icon name="bell" /> 提醒级别: {{ tasks.noteLevel }}</p>
              </div>
            </template>
            <template #right-icon>


            </template>

          </van-cell>
        </van-list>

      </div>
      <div class="empty-state" v-else>
        <van-empty image="search" description="暂无任务，请点击创建任务按钮开始" />
      </div>
    </div>

    <!-- 新增/编辑任务弹窗 -->
    <van-popup v-model:show="showAddTask" position="bottom" :style="{ height: '80%'}" round>
      <div class="config-container">
        <div class="top">
          <span>{{ isEditMode ? '修改任务' : '新增任务' }}</span>
          <van-icon name="cross" @click="cancelTaskEdit" />
        </div>
        <van-form @submit="submitTaskForm">
          <van-field v-model="taskForm.username" name="username" label="用户名" placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]">
            <template #left-icon><van-icon name="user-o" /></template>
          </van-field>

          <van-field v-model="taskForm.password" name="password" label="密码" type="password" placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]">
            <template #left-icon><van-icon name="lock" /></template>
          </van-field>

          <van-field label="上班时间" v-model="taskForm.clockIn" @click="showTime = true, timeType = 'clockIn'" readonly>
            <template #left-icon><van-icon name="sign" /></template>
            <template #right-icon>
              <van-icon name="arrow" />
            </template>
          </van-field>

          <van-field label="下班时间" v-model="taskForm.clockOut" @click="showTime = true, timeType = 'clockOut'" readonly>
            <template #left-icon><van-icon name="completed" /></template>
            <template #right-icon>
              <van-icon name="arrow" />
            </template>
          </van-field>

          <van-field v-model="taskForm.delay" type="digit" label="延迟范围" placeholder="延迟范围(分钟，目标时间往后延迟)">
            <template #left-icon><van-icon name="clock-o" /></template>
          </van-field>

          <van-field v-model="taskForm.email" name="email" label="邮箱" placeholder="请输入邮箱地址"
            :rules="[{ required: true, message: '请填写邮箱' }, { pattern: /.+@.+\..+/, message: '请输入有效的邮箱地址' }]">
            <template #left-icon><van-icon name="envelop-o" /></template>
          </van-field>



          <van-field name="noteLevel" label="提醒级别">
            <template #left-icon><van-icon name="bell" /></template>
            <template #input>
              <van-stepper v-model="taskForm.noteLevel" min="1" max="5" theme="round" />
            </template>
          </van-field>

          <div class="form-actions">
            <van-button round block type="primary" native-type="submit">
              {{ isEditMode ? '保存修改' : '创建任务' }}
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>

    <van-popup v-model:show="showTime" position="bottom" round :style="{ height: '40%' }">
      <van-time-picker v-model="timeValue" title="选择时间" @confirm="timeConfirm" @cancel="showTime = false"
        :columns-type="['hour', 'minute', 'second']" />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getTaskdetail, taskResume, taskPause, taskDelete, taskEnd, taskCreate, taskUpdate, taskExecute } from '@/api/clockIn'
import { showToast, showSuccessToast, showFailToast } from 'vant'

const showAddTask = ref(false)
const loading = ref(false)
const isEditMode = ref(false)
const taskStatus = ref(true)
const showTime = ref(false)
const currentTaskId = ref(null)
const timeType = ref('clockIn')
const timeValue = ref([])
const username = ref(localStorage.getItem("username") || '')

const timeConfirm = (value) => {

  if (timeType.value === 'clockIn') {
    taskForm.value.clockIn = value.selectedValues.join(':')
  } else {
    taskForm.value.clockOut = value.selectedValues.join(':')
  }
  showTime.value = false
}

// 任务列表
const tasks = ref({})

const showTasks = () => {
  if (tasks.value.id) {
    taskForm.value = { ...tasks.value }
    isEditMode.value = true

  }
  showAddTask.value = true
}

// 任务表单
const taskForm = ref({
  username: '',
  password: '',
  clockIn: "09:00:00",
  clockOut: "18:00:00",
  email: '',
  noteLevel: 1,
  delay: 3

})

// 重置表单数据
const resetTaskForm = () => {
  taskForm.value = {
    username: '',
    password: '',
    clockIn: "09:00:00",
    clockOut: "18:00:00",
    email: '',
    noteLevel: 1,
    delay: 3
  }
}

const clearCache= () => {
  localStorage.removeItem('username')
  currentTaskId.value = null
  resetTaskForm()
  tasks.value = {}
  // 页面刷新
  location.reload()
}

// 取消任务编辑
const cancelTaskEdit = () => {
  isEditMode.value = false
  currentTaskId.value = null
  resetTaskForm()
  showAddTask.value = false
}

// 格式化当前时间
const currentTime = ref('')
const currentDate = ref('')

// 定时更新时间
const updateTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })
  currentDate.value = now.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' })
}






// 获取任务列表
const fetchTasks = async () => {
  try {
    loading.value = true
    const res = await getTaskdetail(localStorage.getItem("username"))
    tasks.value = res || {}
    taskStatus.value = res.enable
    currentTaskId.value = res.id || null
  } catch (error) {
    console.error('获取任务列表失败:', error)
    showFailToast('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 手动执行任务
const executeTask = async (id) => {
  try {
    loading.value = true
    await taskExecute(id)
    showSuccessToast('任务已开始执行')
    fetchTasks()
  } catch (error) {
    console.error('执行任务失败:', error)
    showFailToast('执行任务失败')
  } finally {
    loading.value = false
  }
}

// 暂停任务
const pauseTask = async (id) => {
  try {
    loading.value = true
    await taskPause(id)
    showSuccessToast('任务已暂停')
    fetchTasks()
  } catch (error) {
    console.error('暂停任务失败:', error)
    showFailToast('暂停任务失败')
  } finally {
    loading.value = false
  }
}

// 恢复任务
const resumeTask = async (id) => {
  try {
    loading.value = true
    await taskResume(id)
    showSuccessToast('任务已恢复')
    fetchTasks()
  } catch (error) {
    console.error('恢复任务失败:', error)
    showFailToast('恢复任务失败')
  } finally {
    loading.value = false
  }
}

// 删除任务
const deleteTask = async (id) => {
  try {
    loading.value = true
    await taskDelete(id)
    showSuccessToast('任务已删除')
    localStorage.removeItem('username')
    fetchTasks()
  } catch (error) {
    console.error('删除任务失败:', error)
    showFailToast('删除任务失败')
  } finally {
    loading.value = false
  }
}



// 提交任务表单（创建或更新）
const submitTaskForm = async () => {
  try {
    loading.value = true

    if (isEditMode.value && currentTaskId.value) {
      // 更新现有任务
      await taskUpdate({ id: currentTaskId.value, ...taskForm.value })
      showSuccessToast('任务已更新')
    } else {
      // 创建新任务
      await taskCreate({
        ...taskForm.value,
      })
      localStorage.setItem('username', taskForm.value.username)
      showSuccessToast('任务已创建')
    }

    // 重置状态并刷新任务列表
    resetTaskForm()
    isEditMode.value = false
    currentTaskId.value = null
    showAddTask.value = false
    fetchTasks()
  } catch (error) {
    console.error('保存任务失败:', error)
    showFailToast('保存任务失败')
  } finally {
    loading.value = false
  }
}



onMounted(() => {
  updateTime()
  let name = localStorage.getItem("username")
  if (!name) {
    let username = prompt("请输入您的名称", "")
    if (username) {
      localStorage.setItem("username", username)
    }
  }
  setInterval(updateTime, 1000)
  fetchTasks()
})
</script>

<style lang="scss" scoped>
.clock-in {
  padding: 16px;
  width: 100%;
  height: 100vh;
  background-color: #f8f9fa;
  color: #333;
  display: flex;
  flex-direction: column;

  .info-content {
    display: flex;
    flex-direction: column;
    height: 100%;
    max-width: 800px;
    margin: 0 auto;
    width: 100%;

    .info-top {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      margin-bottom: 10px;

      span {
        height: 50px;
        font-size: 22px;
        font-weight: bold;
        color: #1989fa;
        display: flex;
        align-items: center;

        .clock-icon {
          margin-right: 8px;
        }
      }
    }
  }

  .clock-panel {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 10px;
    padding: 24px;
    border-radius: 16px;
    background-color: #ffffff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

    .time-display {
      text-align: center;
      margin-bottom: 24px;
      width: 100%;

      h2 {
        font-size: 42px;
        margin: 0;
        font-weight: bold;
        color: #1989fa;
        letter-spacing: 2px;
      }

      p {
        margin-top: 8px;
        color: #666;
        font-size: 16px;
      }
    }

    .clock-actions {
      display: flex;
      width: 100%;
      gap: 20px;

      .van-button {
        flex: 1;
        border-radius: 8px;
        height: 48px;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }

  .task-list {
    margin-top: 24px;
    overflow-y: auto;
    background-color: #ffffff;
    border-radius: 16px;
    padding: 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

    h3 {
      padding: 0 8px 12px;
      margin-bottom: 10px;
      font-size: 18px;
      font-weight: 600;
      color: #1989fa;
      border-bottom: 1px solid #ebedf0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .van-icon {
        margin-right: 6px;
      }
    }

    .van-cell {
      background-color: transparent;
      border-radius: 8px;
      margin-bottom: 8px;
      padding: 12px 16px;
      transition: all 0.3s;

      &:hover {
        background-color: #f5f7fa;
      }
    }

    .task-actions {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      margin-top: 8px;
      justify-content: flex-end;

      .van-button {
        border-radius: 6px;
      }
    }

    .task-info {
      font-size: 15px;
      color: #666;
      padding: 4px 0;

      p {
        margin: 10px 0px;
        display: flex;
        align-items: center;

        .van-icon {
          margin-right: 6px;
          color: #1989fa;
          font-size: 16px;
        }
      }
    }

    .van-tag {
      padding: 2px 8px;
      font-weight: 500;
      margin-bottom: 8px;
    }
  }

  .empty-state {
    margin-top: 24px;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #ffffff;
    border-radius: 16px;
    padding: 32px 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }

  .btns {
    display: flex;
    justify-content: center;
    width: 100%;
    margin-top: 20px;

    .van-button {
      width: 80%;
      border-radius: 8px;
    }
  }

  .top {
    display: flex;
    justify-content: space-between;
    padding: 16px;
    border-bottom: 1px solid #ebedf0;
    align-items: center;

    span {
      font-size: 18px;
      font-weight: bold;
      color: #1989fa;
    }

    .van-icon {
      border: 1px solid #dcdee0;
      border-radius: 50%;
      padding: 6px;
      font-size: 18px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background-color: #f2f3f5;
      }
    }
  }

  .config-container {
    padding: 0 16px 20px;

    .van-form {
      margin-top: 16px;

      .van-field {
        margin-bottom: 12px;
        border-radius: 8px;
        background-color: #f5f7fa;

        .field-actions {
          display: flex;
          align-items: center;
          gap: 8px;

          .van-icon {
            font-size: 18px;
            color: #1989fa;

            &:first-child {
              padding: 4px;
              border-radius: 50%;
              background-color: rgba(25, 137, 250, 0.1);
            }
          }
        }
      }

      .form-actions {
        margin-top: 24px;

        .van-button {
          height: 44px;
          font-size: 16px;
          font-weight: 500;
        }
      }
    }
  }

  .time-selector {
    display: flex;
    align-items: center;
    gap: 5px;

    .van-stepper {
      width: 28%;
    }

    span {
      font-size: 16px;
      font-weight: bold;
    }
  }
}

// 弹窗样式优化
:deep(.van-popup) {
  border-radius: 16px 16px 0 0;
  overflow: hidden;
}

:deep(.van-time-picker) {
  --van-picker-background: #ffffff;

  .van-picker__confirm {
    color: #1989fa;
  }
}

.task-cell {
  font-size: 20px;
  font-weight: bold;
}
</style>